package com.mowh.multithreading.single.threaded.execution.gate;

/**
 * @author mowh1gd
 * @create 2023/11/9 14:35
 */
public class Gate { //扮演SharedResource
    private int counter = 0;
    private String name = "Nobody";
    private String address = "Nowhere";

    public synchronized void pass(String name, String address) { //扮演SharedResource的unsafeMethod，需synchronized声名方法来设置同步锁，保护线程（物理锁，实例自带的锁）
        this.counter++;
        this.name = name;
        this.address = address;
        check();
    }

    @Override
    public synchronized String toString() { //扮演SharedResource的unsafeMethod，需synchronized声名方法来设置同步锁，保护线程
        return "No." + counter + ": " + name + ", " + address;
    }

    private void check() {
        if (name.charAt(0) != address.charAt(0)) {
            System.out.println("***** BROKEN ***** " + toString());
        }
    }
}
